package com.fyx.timedTask;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fyx.config.*;
import com.fyx.entity.*;
import com.fyx.mapper.CardInfoMapper;
import com.fyx.mapper.OverviewMapper;
import com.fyx.mapper.PropsInfoMapper;
import com.fyx.mapper.SysDictDetailMapper;
import com.fyx.until.DateUtil;
import com.fyx.utils.StringUtils;
import com.mongodb.client.AggregateIterable;
import com.mongodb.client.MongoCursor;
import lombok.extern.slf4j.Slf4j;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 道具消耗分类统计
 */
@Slf4j
@Component(value="OverviewTask")
public class OverviewTask {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Resource(name = SecondaryMongoConfig.MONGO_TEMPLATE)
    private MongoTemplate secondaryMongoTemplate;

    @Resource(name = FiveMongoConfig.MONGO_TEMPLATE)
    private MongoTemplate fiveMongoTemplate;

    @Resource(name = SixthMongoConfig.MONGO_TEMPLATE)
    private MongoTemplate sixthMongoTemplate;

    @Resource(name = NinethMongoConfig.MONGO_TEMPLATE)
    private MongoTemplate ninethMongoTemplate;

    @Resource(name = TenthMongoConfig.MONGO_TEMPLATE)
    private MongoTemplate tenthMongoTemplate;

    @Autowired
    private OverviewMapper overviewMapper;

    public void run(){
        long time = DateUtil.getDayBegin().getTime()/1000;
        long nowTime=new Date().getTime()/1000;
        String tableName=DateUtil.timeStamp2Date(time+"","yyyyMM");
        if((time+3600)>nowTime){
            time=DateUtil.getBeginDayOfYesterday().getTime()/1000;
            if(!DateUtil.timeStamp2Date(time+"","yyyyMM").equals(DateUtil.timeStamp2Date(nowTime+"","yyyyMM"))){
                tableName =DateUtil.timeStamp2Date(time+"","yyyyMM");
            }
        }
        long endTime=time+86400;
       // time = DateUtil.getBeginDayOfYesterday().getTime()/1000-2073600;
      //  endTime=DateUtil.getEndDayOfYesterDay().getTime()/1000-2073600;
        record();
        recordByProp(time,endTime);
        recordByCard(time,endTime,tableName);
        log.info("道具消耗分类统计：执行完毕=======================");
    }

    public void record(){
        //道具消耗分类统计
        long dayBeginTime = DateUtil.getDayBegin().getTime()/1000;
        long nowTime=new Date().getTime()/1000;
        if(dayBeginTime==nowTime){
            dayBeginTime=DateUtil.getBeginDayOfYesterday().getTime()/1000;
        }
        long dayEndTime = DateUtil.getDayEnd().getTime()/1000;
        Document sub_match = new Document();
        sub_match.put("day", new Document("$gte", dayBeginTime).append("$lte", dayEndTime));
        Document match = new Document("$match", sub_match);
        List<Document> aggregateList = new ArrayList<Document>();
        aggregateList.add(match);
        AggregateIterable<Document> todayGoodsOverview =  mongoTemplate.getCollection("goods_overview").aggregate(aggregateList);
        MongoCursor<Document> iterator = todayGoodsOverview.iterator();
        List<Overview> list1 = new ArrayList<>();
        while (iterator.hasNext()) {
            Map mapList = iterator.next();
            String channel =  mapList.get("channel")+"";
            for (Object key : mapList.keySet()) {
                String mapKey = (String) key;
                if (!mapKey.equals("_id") && !mapKey.equals("day") && !mapKey.equals("channel")) {
                    Overview overview = new Overview();
                    String PropsValue=mapList.get(mapKey)+"";
                    overview.setChannel(channel);
                    overview.setOverviewName(mapKey);
                    overview.setOverviewValue(PropsValue);
                    overview.setOverviewType("0");
                    overview.setAddTime(dayBeginTime);
                    list1.add(overview);
                }
            }
        }
        iterator.close();
        QueryWrapper<Overview> wrapper =new QueryWrapper<>();
        wrapper.ge("add_time",dayBeginTime);
        wrapper.eq("overview_type","0");
        if(list1.size()>0){
            overviewMapper.delete(wrapper);
            overviewMapper.insertList(list1);
        }

    }
    @Autowired
    private SysDictDetailMapper sysDictDetailMapper;

    @Autowired
    private CardInfoMapper cardInfoMapper;

    @Autowired
    private PropsInfoMapper propsInfoMapper;

    public void recordByProp(long time,long endTime){

        QueryWrapper<SysDictDetail> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("dict_id", 15);
        wrapper1.eq("dict_sort", 10);
        wrapper1.orderByDesc("dict_sort");
        List<SysDictDetail> list1 = sysDictDetailMapper.selectList(wrapper1);
        wrapper1 = new QueryWrapper<>();
        wrapper1.eq("dict_id", 16);
        wrapper1.lt("dict_sort", 987).or().eq("dict_sort",999);
        wrapper1.orderByDesc("dict_sort");
        List<SysDictDetail> list = sysDictDetailMapper.selectList(wrapper1);
        if(list.size()>0&&list1.size()>0){
            for(SysDictDetail sysDictDetail1:list){
                PropsInfoEntity propsInfoEntity = new PropsInfoEntity();
                propsInfoEntity.setTime((int)time);
                propsInfoEntity.setChannel(sysDictDetail1.getValue());
                if(sysDictDetail1.getDictSort()==900) {
                    propsInfoEntity.setTheFather("total");
                }else if(sysDictDetail1.getDictSort()==910){
                    propsInfoEntity.setTheFather("totalcl");
                }else if(sysDictDetail1.getDictSort()==920){
                    propsInfoEntity.setTheFather("totalapp");
                }else if(sysDictDetail1.getDictSort()>0){
                    if(sysDictDetail1.getValue().equals("h5zhsmjcl_wechat")){
                        propsInfoEntity.setTheFather("zsmjxl_total");
                    }else if(sysDictDetail1.getValue().indexOf("gdmj")==0){
                        propsInfoEntity.setTheFather(sysDictDetail1.getValue().split("_")[0]+ "_app_total");
                    }else {
                        propsInfoEntity.setTheFather(sysDictDetail1.getValue().split("_")[0].replace("h5", "") + "_total");
                    }
                }
                String st="";
                for(SysDictDetail sysDictDetail:list1){
                    Criteria criteria=new Criteria();
                    criteria.and("time_end").gte(time).lte(endTime);
                    criteria.and("mall_id").is(Integer.parseInt(sysDictDetail.getValue()));
                    if(sysDictDetail1.getDictSort()!=null&&sysDictDetail1.getDictSort()<999){
                        if(sysDictDetail1.getDictSort()==900||sysDictDetail1.getDictSort()==910||sysDictDetail1.getDictSort()==920){
                            criteria.and("channel").regex(sysDictDetail1.getValue().split("_")[0]);
                        }else {
                            criteria.and("channel").is(sysDictDetail1.getValue());
                        }
                    }
                    Aggregation aggregation = Aggregation.newAggregation(
                            Aggregation.match(criteria),
                            Aggregation.group().sum("total_fee").as("v1")
                    );
                    AggregationResults<StaticeEntity> ar ;
                    if(sysDictDetail1.getValue().equals("totalcl")||sysDictDetail1.getValue().indexOf("cl_")>0){
                        ar = fiveMongoTemplate.aggregate(aggregation, "order", StaticeEntity.class);
                    }else if(sysDictDetail1.getValue().equals("totalapp")||(sysDictDetail1.getValue().indexOf("gdmj")==0&&sysDictDetail1.getDictSort()!=900&&sysDictDetail.getDictSort()!=910)){
                        ar = ninethMongoTemplate.aggregate(aggregation, "order", StaticeEntity.class);
                    }
                    else {
                        ar = mongoTemplate.aggregate(aggregation, "order", StaticeEntity.class);
                    }
                    List<StaticeEntity> list3 = ar.getMappedResults();

                    if (list3.size() > 0) {
                       st+=sysDictDetail.getValue()+"-"+list3.get(0).getV1()/100+"/";
                    }else {
                        st+=sysDictDetail.getValue()+"-0/";
                    }
                }
                propsInfoEntity.setTheValues(st);

                QueryWrapper<PropsInfoEntity> wrapper=new QueryWrapper<>();
                wrapper.eq("time",time);
                wrapper.eq("channel",propsInfoEntity.getChannel());
                if(StringUtils.isNotEmpty(propsInfoEntity.getTheFather())){
                    wrapper.eq("the_father",propsInfoEntity.getTheFather());
                }
                PropsInfoEntity propsInfoEntity1= propsInfoMapper.selectOne(wrapper);
                if(propsInfoEntity1==null) {
                    propsInfoMapper.insert(propsInfoEntity);
                }else {
                    propsInfoMapper.update(propsInfoEntity,wrapper);
                }
           }
        }
    }

    public void recordByCard(long time,long endTime,String tableName) {
        String daiTable="diamond_buy_log_"+tableName;
        tableName = "props_rec_" + tableName;

        QueryWrapper<SysDictDetail> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("dict_id", 16);
        wrapper1.le("dict_sort", 950).or().eq("dict_sort", 999);
        wrapper1.orderByDesc("dict_sort");
        List<SysDictDetail> list1 = sysDictDetailMapper.selectList(wrapper1);
        if (list1.size() > 0) {
            for (SysDictDetail sysDictDetail1 : list1) {
                CardInfoEntity cardInfoEntity=new CardInfoEntity();
                cardInfoEntity.setTime(time);
                cardInfoEntity.setChannel(sysDictDetail1.getValue());
                if(sysDictDetail1.getDictSort()!=null&&sysDictDetail1.getDictSort()<999){
                    if(sysDictDetail1.getDictSort()!=null&&sysDictDetail1.getDictSort()==900) {
                        cardInfoEntity.setTheFather("total");
                    }else if(sysDictDetail1.getDictSort()!=null&&sysDictDetail1.getDictSort()==910){
                        cardInfoEntity.setTheFather("totalcl");
                    }else if(sysDictDetail1.getDictSort()!=null&&sysDictDetail1.getDictSort()==920){
                        cardInfoEntity.setTheFather("totalapp");
                    }else {
                        if(sysDictDetail1.getValue().equals("h5zhsmjcl_wechat")){
                            cardInfoEntity.setTheFather("zsmjxl_total");
                        }else if(sysDictDetail1.getValue().indexOf("gdmj")==0){
                            cardInfoEntity.setTheFather(sysDictDetail1.getValue().split("_")[0]+"_app_total");
                        }else {
                            cardInfoEntity.setTheFather(sysDictDetail1.getValue().split("_")[0].replace("h5","")+"_total");
                        }
                    }
                }

                cardInfoEntity.setCaiFuka(getCardNum(time,endTime,sysDictDetail1,tableName,100120,0)+"/"+getCardNum(time,endTime,sysDictDetail1,tableName,100120,1));
                cardInfoEntity.setPmFuka(getCardNum(time,endTime,sysDictDetail1,tableName,100121,0)+"/"+getCardNum(time,endTime,sysDictDetail1,tableName,100121,1));
                cardInfoEntity.setTuFuka(getCardNum(time,endTime,sysDictDetail1,tableName,100122,0)+"/"+getCardNum(time,endTime,sysDictDetail1,tableName,100122,1));
                cardInfoEntity.setJuFuka(getCardNum(time,endTime,sysDictDetail1,tableName,100123,0)+"/"+getCardNum(time,endTime,sysDictDetail1,tableName,100123,1));
                cardInfoEntity.setCaiJiabei(getCardNum(time,endTime,sysDictDetail1,tableName,100112,0)+"/"+getCardNum(time,endTime,sysDictDetail1,tableName,100112,1));
                cardInfoEntity.setPmJiabei(getCardNum(time,endTime,sysDictDetail1,tableName,100113,0)+"/"+getCardNum(time,endTime,sysDictDetail1,tableName,100113,1));
                cardInfoEntity.setTuJiabei(getCardNum(time,endTime,sysDictDetail1,tableName,100114,0)+"/"+getCardNum(time,endTime,sysDictDetail1,tableName,100114,1));
                cardInfoEntity.setJuJiabei(getCardNum(time,endTime,sysDictDetail1,tableName,100115,0)+"/"+getCardNum(time,endTime,sysDictDetail1,tableName,100115,1));
                cardInfoEntity.setCaiFengding(getCardNum(time,endTime,sysDictDetail1,tableName,100116,0)+"/"+getCardNum(time,endTime,sysDictDetail1,tableName,100116,1));
                cardInfoEntity.setPmFengding(getCardNum(time,endTime,sysDictDetail1,tableName,100117,0)+"/"+getCardNum(time,endTime,sysDictDetail1,tableName,100117,1));
                cardInfoEntity.setTuFengding(getCardNum(time,endTime,sysDictDetail1,tableName,100118,0)+"/"+getCardNum(time,endTime,sysDictDetail1,tableName,100118,1));
                cardInfoEntity.setZimo(getCardNum(time,endTime,sysDictDetail1,tableName,100015,0)+"/"+getCardNum(time,endTime,sysDictDetail1,tableName,100015,1));
                cardInfoEntity.setPeng(getCardNum(time,endTime,sysDictDetail1,tableName,100016,0)+"/"+getCardNum(time,endTime,sysDictDetail1,tableName,100016,1));
                cardInfoEntity.setBoom(getCardNum(time,endTime,sysDictDetail1,tableName,100017,0)+"/"+getCardNum(time,endTime,sysDictDetail1,tableName,100017,1));
                cardInfoEntity.setXixiLao(getCardNum(time,endTime,sysDictDetail1,tableName,100068,0)+"/"+getCardNum(time,endTime,sysDictDetail1,tableName,100068,1));
                cardInfoEntity.setXixiLao(getCardNum(time,endTime,sysDictDetail1,tableName,100068,0)+"/"+getCardNum(time,endTime,sysDictDetail1,tableName,100068,1));


                Criteria criteria=new Criteria();
                criteria.and("time").gte(time).lte(endTime);
                criteria.and("mall_id").is(500288);
                if(sysDictDetail1.getDictSort()!=null&&sysDictDetail1.getDictSort()>0){
                    if(sysDictDetail1.getDictSort()==900||sysDictDetail1.getDictSort()==910){
                        criteria.and("channel").regex(sysDictDetail1.getValue().split("_")[0]);
                    }else {
                        criteria.and("channel").is(sysDictDetail1.getValue());
                    }
                }
                Aggregation aggregation = Aggregation.newAggregation(
                        Aggregation.match(criteria),
                        Aggregation.group().sum("num").as("num")
                );
                AggregationResults<TaskEntity> ar ;
                if(sysDictDetail1.getValue().equals("totalcl")||sysDictDetail1.getValue().indexOf("cl_")>0){
                    ar = sixthMongoTemplate.aggregate(aggregation, daiTable, TaskEntity.class);
                }else if(sysDictDetail1.getValue().equals("totalapp")||(sysDictDetail1.getValue().indexOf("gdmj")==0&&sysDictDetail1.getDictSort()!=900)){
                    ar = tenthMongoTemplate.aggregate(aggregation, daiTable, TaskEntity.class);
                }else {
                    ar = secondaryMongoTemplate.aggregate(aggregation, daiTable, TaskEntity.class);
                }
                List<TaskEntity> list = ar.getMappedResults();
                if (list.size() > 0) {
                    cardInfoEntity.setMonthsCard(list.get(0).getNum()+"/");
                }else {
                    cardInfoEntity.setMonthsCard("0/");
                }
                criteria=new Criteria();
                criteria.and("time").gte(time).lte(endTime);
                criteria.and("mall_id").is(500289);
                if(sysDictDetail1.getDictSort()!=null&&sysDictDetail1.getDictSort()>0){
                    if(sysDictDetail1.getDictSort()==900||sysDictDetail1.getDictSort()==910){
                        criteria.and("channel").regex(sysDictDetail1.getValue().split("_")[0]);
                    }else {
                        criteria.and("channel").is(sysDictDetail1.getValue());
                    }
                }
                aggregation = Aggregation.newAggregation(
                        Aggregation.match(criteria),
                        Aggregation.group().sum("num").as("num")
                );
                if(sysDictDetail1.getValue().equals("totalcl")||sysDictDetail1.getValue().indexOf("cl_")>0){
                    ar = sixthMongoTemplate.aggregate(aggregation, daiTable, TaskEntity.class);
                } else if(sysDictDetail1.getValue().equals("totalapp")||(sysDictDetail1.getValue().indexOf("gdmj")==0&&sysDictDetail1.getDictSort()!=900)){
                    ar = tenthMongoTemplate.aggregate(aggregation, daiTable, TaskEntity.class);
                }
                else {
                    ar = secondaryMongoTemplate.aggregate(aggregation, daiTable, TaskEntity.class);
                }
                list = ar.getMappedResults();
                if (list.size() > 0) {
                    cardInfoEntity.setMonthsCard(cardInfoEntity.getMonthsCard()+ list.get(0).getNum()+"/");
                }else {
                    cardInfoEntity.setMonthsCard(cardInfoEntity.getMonthsCard()+"0/");
                }
                criteria=new Criteria();
                criteria.and("time").gte(time).lte(endTime);
                criteria.and("mall_id").is(500290);
                if(sysDictDetail1.getDictSort()!=null&&sysDictDetail1.getDictSort()>0){
                    if(sysDictDetail1.getDictSort()==900||sysDictDetail1.getDictSort()==910){
                        criteria.and("channel").regex(sysDictDetail1.getValue().split("_")[0]);
                    }else {
                        criteria.and("channel").is(sysDictDetail1.getValue());
                    }
                }
                aggregation = Aggregation.newAggregation(
                        Aggregation.match(criteria),
                        Aggregation.group().sum("num").as("num")
                );
                if(sysDictDetail1.getValue().equals("totalcl")||sysDictDetail1.getValue().indexOf("cl_")>0){
                    ar = sixthMongoTemplate.aggregate(aggregation, daiTable, TaskEntity.class);
                }else if(sysDictDetail1.getValue().equals("totalapp")||(sysDictDetail1.getValue().indexOf("gdmj")==0&&sysDictDetail1.getDictSort()!=900)){
                    ar = tenthMongoTemplate.aggregate(aggregation, daiTable, TaskEntity.class);
                }
                else {
                    ar = secondaryMongoTemplate.aggregate(aggregation, daiTable, TaskEntity.class);
                }

                list = ar.getMappedResults();
                if (list.size() > 0) {
                    cardInfoEntity.setMonthsCard(cardInfoEntity.getMonthsCard()+ list.get(0).getNum());
                }else {
                    cardInfoEntity.setMonthsCard(cardInfoEntity.getMonthsCard()+"0");
                }


                QueryWrapper<CardInfoEntity> wrapper=new QueryWrapper<>();
                wrapper.eq("time",time);
                wrapper.eq("channel",cardInfoEntity.getChannel());
                if(StringUtils.isNotEmpty(cardInfoEntity.getTheFather())) {
                    wrapper.eq("the_father", cardInfoEntity.getTheFather());
                }

                CardInfoEntity cardInfoEntity1= cardInfoMapper.selectOne(wrapper);
                    System.out.println(cardInfoEntity1);
                if(cardInfoEntity1==null) {
                    cardInfoMapper.insert(cardInfoEntity);
                }else {
                    cardInfoMapper.update(cardInfoEntity,wrapper);
                }

            }
        }
    }

    private Long getCardNum(Long time,Long endTime,SysDictDetail sysDictDetail,String tableName,Integer id,Integer num){
        Criteria criteria=new Criteria();
        criteria.and("time").gte(time).lte(endTime);
        criteria.and("name").is(id);
        if(num==0) {
            criteria.and("num").gt(0);
        }else {
            criteria.and("num").lt(0);
        }
        if(sysDictDetail.getDictSort()!=null&&sysDictDetail.getDictSort()>0){
            if(sysDictDetail.getDictSort()==900||sysDictDetail.getDictSort()==910){
                criteria.and("channel").regex(sysDictDetail.getValue().split("_")[0]);
            }else {
                criteria.and("channel").is(sysDictDetail.getValue());
            }
        }
        Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group().sum("num").as("num")
        );
        AggregationResults<TaskEntity> ar ;
        if(sysDictDetail.getValue().equals("totalcl")||sysDictDetail.getValue().indexOf("cl_")>0){
            ar = sixthMongoTemplate.aggregate(aggregation, tableName, TaskEntity.class);
        }else if(sysDictDetail.getValue().equals("totalapp")||(sysDictDetail.getValue().indexOf("gdmj")==0&&sysDictDetail.getDictSort()!=900&&sysDictDetail.getDictSort()!=910)){
            ar = tenthMongoTemplate.aggregate(aggregation, tableName, TaskEntity.class);
        }
        else {
            ar = secondaryMongoTemplate.aggregate(aggregation, tableName, TaskEntity.class);
        }
        List<TaskEntity> list = ar.getMappedResults();
        if (list.size() > 0) {
            return  list.get(0).getNum();
        }else {
            return 0l;
        }
    }
}
